package com.kyh.service.sys.impl;

import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kyh.service.sys.AdminService;
import com.kyh.sys.entity.Admin;
import com.kyh.sys.entity.Adminlog;
import com.kyh.sys.entity.Imgcode;
import com.kyh.sys.entity.Role;
import com.kyh.sys.mapper.AdminMapper;
import com.kyh.sys.mapper.AdminlogMapper;
import com.kyh.sys.mapper.ImgcodeMapper;
import com.kyh.util.CheckUtil;
import com.kyh.util.ReqUtil;
import com.kyh.vo.BootstrapTableVoJA;
import com.kyh.vo.R;

@Service("adminService")
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private AdminlogMapper adminlogMapper;
    @Autowired
    private ImgcodeMapper imgcodeMapper;

	@Override
	@Transactional
	public R add(Admin entity) throws Exception {
		
		if (!CheckUtil.notNull(entity.getAdminloginname())) {
			return R.error("登录名不能为空");
		}
		
		if (!CheckUtil.notNull(entity.getAdminpassword())) {
			return R.error("密码不能为空");
		}
		
		if (!CheckUtil.notNull(entity.getRoleId())) {
			return R.error("角色不能为空");
		}
		
        if (new Admin().setAdminloginname(entity.getAdminloginname()).queryFirst() != null) {
        	return R.error("该账号已存在");
        }
        
        // 验证角色
        if (new Role().setRoleId(entity.getRoleId()).queryFirst() == null) {
			return R.error("所选角色不存在");
		}
		
		// 添加数据
		if (adminMapper.insert(entity) != 1) {
			throw new RuntimeException("失败");
		}
		
		return R.ok();
	}

	@Override
	public R edit(Admin entity) throws Exception {
		
		Long adminId = entity.getAdminid();
		Admin admin = new Admin().setAdminid(adminId).queryFirst();
		if (admin == null) {
			return R.error("该管理员不存在");
		}
        
        // 验证角色
		Long roleId = entity.getRoleId();
		if (roleId != null) {
	        Role role = new Role().setRoleId(roleId).queryFirst();
	        if (role == null) {
				return R.error("所选角色不存在");
			}
		}
		
		// 验证登录名
		String adminloginname = entity.getAdminloginname();
		if (adminloginname != null) {
			if (!adminloginname.equals(admin.getAdminloginname())) {
				if (new Admin().setAdminloginname(adminloginname).count() > 0) {
					return R.error("该登录名已存在");
				}
			}
		}
		
		if (adminMapper.update(entity) != 1) {
			throw new RuntimeException("失败");
		}
		
		return R.ok();
	}

    @Override
    public R login(
    		HttpServletRequest request,
    		HttpServletResponse response,
    		String adminloginname,
    		String adminpassword,
			String imgcodevalue
    		) {
		
		// 验证登录名
		if (!CheckUtil.notNull(adminloginname)) {
			return R.error("登录名不能为空");
		}
		
		// 验证密码
		if (!CheckUtil.notNull(adminpassword)) {
			return R.error("密码不能为空");
		}
		
		String imgcodeip = ReqUtil.getIpAddr(request);
		
		// 验证图形验证码
		if (!CheckUtil.notNull(imgcodevalue)) {
			return R.error("图形验证码不能为空");
		}

		// 验证图形验证码
		Imgcode imgcode = new Imgcode().setImgcodeip(imgcodeip).queryFirst();
		if (imgcode == null) {
			return R.error("请刷新重试");
		}
		if (!imgcodevalue.equals(imgcode.getImgcodevalue())) {
			imgcodeMapper.deleteByIp(imgcodeip);
			return R.error("图形验证码有误");
		}
    	
        Admin admin = new Admin().setAdminloginname(adminloginname).addField("A.adminpassword as adminpassword").queryFirst();
        if (admin == null) {
            return R.error("账号不存在");
        }
        if (!adminpassword.equals(admin.getAdminpassword())) {
            return R.error("密码不正确");
        }
        
        String admintoken = UUID.randomUUID().toString();
        admin.setAdmintoken(admintoken);
        adminMapper.update(admin);

        Long adminId = admin.getAdminid();
        String value = admintoken + "_" + adminId;
        Cookie cookie = new Cookie(ReqUtil.ADMIN_TOKEN, value);
        cookie.setMaxAge(2 * 24 * 60 * 60);
        response.addCookie(cookie);
        
        // 删除图形验证码
        imgcodeMapper.deleteByIp(imgcodeip);

        Adminlog adminlog = Adminlog.adminlog(
        		imgcodeip,
        		"登录",
        		adminId
        		);
        adminlogMapper.insert(adminlog);
        return R.ok();
    }

    @Override
    @Transactional
    public R deleteFalse(Long adminid) throws Exception {
    	
    	if (adminMapper.deleteFalse(adminid) != 1) {
			throw new RuntimeException("失败");
		}
        return R.ok();
    }

    @Override
    @Transactional
    public R deleteTrue(Long adminid) {
    	
    	adminMapper.deleteTrue(adminid);
        return R.ok();
    }

	@Override
	public BootstrapTableVoJA search(Admin cond) {
		
		List<Map<String, Object>> listMap = cond.queryMap();
		
		int total = cond.count();
		
        BootstrapTableVoJA vo = new BootstrapTableVoJA();
        vo.setRowsByListMap(listMap);
        vo.setTotal(total);
        
        return vo;
	}
}
